<?php

class Admin extends Core {
    
    function __construct() {
        
        parent::__construct();
        
        if (!$this->usr->check_rights('admin')) {
            
            show_error('Нет доступа!!!');
        }
        
        $this->load->model('modmanager');
        $this->load->language('admin');
        $this->load->helper('adminhelp');
        $this->load->helper('language');
    }
    
    
    /**
     * Главная страница модуля
     */
    public function index() {
        
        parent::render(array('tree' => $this->load->tree()), 'page/index');
    }
    
    
    /**
     * Страница модуля
     */
    public function modul($modul, $method = 'index') {
        
        //Загрузка нужного модуля
        $class  = 'pr_'.$modul;
        
        $is_modul = $this->modmanager->get_modul($modul);
        
        if ($is_modul !== false && is_object($is_modul) && $is_modul->admin) {
            
            $this->set_bread_crumbs(lang('menu_modules'), 'moduls');
            $this->set_bread_crumbs($is_modul->title, 'modul/'.$is_modul->code);
            
            $arg = func_get_args();
            $arg = array_merge(array($modul.'/'.$class.'/'.$method), array_slice($arg, 2));
            $content = call_user_func_array(array('modules', 'run'), $arg);
        }
        else {
            
            modul_redirect();
        }
        
        parent::render($content);
    }
    
    
    /**
     * Редактирование страницы
     */
    public function edit($uri) {
        
        $this->load->helper('form');
        $this->load->model('adminmodel');
        
        $data['page'] = $this->load->page_info(false, $uri);
        
        if ( $this->input->post('edit', TRUE) ) {
            
            $this->load->library('form_validation');
            
            if ($uri != 'www') {
            
                $this->form_validation->set_rules('parent_id',  'lang:tree_parent_id',   'trim|required|xss_clean');
                $this->form_validation->set_rules('uri', 		'lang:tree_uri', 	'trim|required|min_length[2]|xss_clean');
            }
            
            $this->form_validation->set_rules('title',      'lang:tree_title',   'trim|required|min_length[2]|xss_clean');
            $this->form_validation->set_rules('modul', 		'lang:tree_modul', 	'trim|required|min_length[2]|xss_clean');
            $this->form_validation->set_rules('method', 	'lang:tree_method', 	'trim|required|xss_clean');
            $this->form_validation->set_rules('mask', 		'lang:tree_mask', 	'trim|xss_clean');
            $this->form_validation->set_rules('parametrs', 	'lang:tree_parametrs', 'trim|xss_clean');
            $this->form_validation->set_rules('template', 	'lang:tree_template', 'trim|required|xss_clean');
            $this->form_validation->set_rules('global_template', 'lang:tree_global_template', 'trim|required|xss_clean');
            $this->form_validation->set_rules('description',  'lang:description',   'trim|xss_clean');
            $this->form_validation->set_rules('keywords',  'lang:keywords',   'trim|xss_clean');
            $this->form_validation->set_rules('settings[]',   '',   '');
            
            //Правила для валидации параметров модуля
            $modul = $this->modmanager->get_modul($data['page']['modul']);
            
            if (isset($modul->parametrs[$data['page']['method']])) {
                
                $params = $modul->parametrs[$data['page']['method']];
                
                foreach($params['validation'] as $name => $valid) {
                    
                    $this->form_validation->set_rules('settings['.$name.']',   $params['parametrs'][$name][0],   $valid);
                }
            }
            
            if ( $this->form_validation->run() ) {
                
                $data['notification'] = lang('edit_page_success');
                
                $this->adminmodel->page_edite($data['page']['id'], 
                      set_value('parent_id',1), set_value('uri', 'www'), set_value('title'), 
                      set_value('modul'), set_value('method', 'index'), set_value('mask'),
                      set_value('parametrs'), set_value('template', 'content'), set_value('global_template', 'default'),
                      set_value('description'), set_value('keywords'), set_value('settings[]'));
            
                $this->adminmodel->edite_rights($uri, $this->input->post('rights', true));
                $this->adminmodel->event_reset_cache();
            }
            else {
                
                $data['notification'] = $this->form_validation->error_string();
            }
        }
        
        foreach($this->load->tree() as $row) {
            
            if ($uri != $row['uri']) {
            
                $data['pages'][$row['id']] = nbs($row['level']*2).$row['title'];
            }
        }
        
        foreach($this->modmanager->get_modules() as $mod) {
            
            $data['modules'][$mod->code] = $mod->title;
            
            if ($mod->code == $data['page']['modul']) {
                
                $data['methods'] = $mod->methods;
            }
        }
        
        
        $data['rights'] = $this->adminmodel->get_rights($uri)->result_array();
        $data['templates'] = $this->adminmodel->get_templates();
        $data['templates_files'] = $this->adminmodel->get_template_files($data['page']['global_template']);
        
        parent::render($data, 'page/edit');
    }
    
    
    /**
     * Создание новой страницы
     */
    public function add() {
        
        $this->load->helper('form');
        $this->load->model('adminmodel');
        
        if ( $this->input->post('add', TRUE) ) {
            
            $this->load->library('form_validation');
            
            $this->form_validation->set_rules('parent_id',  'lang:tree_parent_id',   'trim|required|xss_clean');
            $this->form_validation->set_rules('uri',        'lang:tree_uri',     'trim|required|min_length[2]|xss_clean');
            $this->form_validation->set_rules('title',      'lang:tree_title',   'trim|required|min_length[2]|xss_clean');
            $this->form_validation->set_rules('modul',      'lang:tree_modul',   'trim|required|min_length[2]|xss_clean');
            $this->form_validation->set_rules('method',     'lang:tree_method',  'trim|required|xss_clean');
            $this->form_validation->set_rules('mask',       'lang:tree_mask',    'trim|xss_clean');
            $this->form_validation->set_rules('parametrs',  'lang:tree_parametrs', 'trim|xss_clean');
            $this->form_validation->set_rules('template',   'lang:tree_template', 'trim|required|xss_clean');
            $this->form_validation->set_rules('global_template', 'lang:tree_global_template', 'trim|required|xss_clean');
            $this->form_validation->set_rules('description',  'lang:description',   'trim|xss_clean');
            $this->form_validation->set_rules('keywords',  'lang:keywords',   'trim|xss_clean');
            $this->form_validation->set_rules('settings[]',   '',   '');
            
            //Правила для валидации параметров модуля
            $modul = $this->modmanager->get_modul(set_value('modul'));
            
            if (isset($modul->parametrs[set_value('method', 'index')])) {
                
                $params = $modul->parametrs[set_value('method', 'index')];
                
                foreach($params['validation'] as $name => $valid) {
                    
                    $this->form_validation->set_rules('settings['.$name.']',   $params['parametrs'][$name][0],   $valid);
                }
            }
            
            if ( $this->form_validation->run() ) {
                
                $data['notification'] = lang('create_page_success');
                
                $this->adminmodel->page_add( 
                      set_value('parent_id',1), set_value('uri'), set_value('title'), 
                      set_value('modul'), set_value('method', 'index'), set_value('mask'),
                      set_value('parametrs'), set_value('template', 'content'), set_value('global_template', 'default'),
                      set_value('description'), set_value('keywords'), set_value('settings[]'));
            
                $this->adminmodel->add_rights(set_value('uri'), $this->input->post('rights', true));
                $this->adminmodel->event_reset_cache();
            }
            else {
                
                $data['notification'] = $this->form_validation->error_string();
            }
        }
        
        foreach($this->load->tree() as $row) {
            
                $data['pages'][$row['id']] = nbs($row['level']*2).$row['title'];
        }
        
        //Загрузка модулей и методов
        $is_first = false;
        foreach($this->modmanager->get_modules() as $mod) {
            
            $data['modules'][$mod->code] = $mod->title;
            
            if (!$is_first) {
                
                $data['methods'] = $mod->methods;
                $is_first = true;
            }
        }
        
        $data['groups'] = $this->adminmodel->get_groups()->result_array();
        $data['templates'] = $this->adminmodel->get_templates();
        $data['templates_files'] = $this->adminmodel->get_template_files(current($data['templates']));
        
        parent::render($data, 'page/add');
    }
    
    
    /**
     * Удаление страницы
     */
    public function del($uri) {
        
        $this->load->model('adminmodel');
        $this->adminmodel->page_del($uri);
        $this->adminmodel->del_rights($uri);
        $this->adminmodel->event_reset_cache();
        
        modul_redirect();
    }
    
    
    /**
     * Настройки сайта
     * @param $modul - модуль
     */
    public function settings($modul = 'core') {
        
        $this->load->helper('form');
        $this->load->model('modsettings');
        $this->load->model('adminmodel');
        
        if ($this->input->post('settings_save')) {
            
            $this->modsettings->update($modul);
            $data['updated'] = lang('success');
            
            $this->adminmodel->event_reset_cache();
        }
        
        $this->set_bread_crumbs(lang('menu_settings'), 'settings');
        
        $data['table'] = $this->modsettings->settings($modul);
        
        parent::render($data, 'settings');
    }
    
    
    public function params_page($modul = false, $method = false, $params = false) {
        
        $this->load->helper('form');
        $this->load->model('adminmodel');
        
        $modul  = ($modul  === false) ? $this->input->post('modul')  : $modul;
        $method = ($method === false) ? $this->input->post('method') : $method;
        $params = ($params === false) ? $this->input->post('params') : $params;
        
        if ($params !== false) {
            
            $properties = $this->load->page_info_byid($params);
            
            if ($properties['modul'] == $modul && $properties['method'] == $method) {
                
                $params = $properties['settings'];
            }
            else {
                
                $params = false;
            }
        }
        
        $mod = $this->modmanager->get_modul($modul);
        
        $data['fields'] = $this->adminmodel->get_page_form_params($method, $mod, $params);
        parent::render($data, 'widget/params');
    }
    
    
    /**
     * Загрузка методов для модуля
     * @param $modul string
     */
    public function load_methods($modul='page') {
        
        $modul = ($this->input->post('id') !== false) ? $this->input->post('id') : $modul;
        
        $mod = $this->modmanager->get_modul($modul);
        
        parent::render(array('array' => $mod->methods, 'name' => 'method'), 'ajax_select');
    }
    
    
    /**
     * Загрузка файлов шаблона
     * @param $template string 
     * @return unknown_type
     */
    public function load_templates($template = 'default') {
        
        $template = ($this->input->post('id') !== false) ? $this->input->post('id') : $template;
        
        $this->load->model('adminmodel');
        
        parent::render(array('array' => $this->adminmodel->get_template_files($template), 'name' => 'template'), 'ajax_select');
    }
    
    
    public function tool($modul, $class, $method = 'index') {
        
        //Загрузка нужного иструмента
        $class_end  = 'tool_'.$class;
        
        $is_modul = $this->modmanager->get_modul($modul);
        
        if ($is_modul !== false && is_object($is_modul) && isset($is_modul->tools[$class])) {
            
            $this->set_bread_crumbs(lang('menu_tools'), 'tools');
            $this->set_bread_crumbs($is_modul->tools[$class], 'tool/'.$is_modul->code.'/'.$class);
            
            $arg = func_get_args();
            $arg = array_merge(array($modul.'/'.$class_end.'/'.$method), array_slice($arg, 3));
            $content = call_user_func_array(array('modules', 'run'), $arg);
        }
        else {
            
            modul_redirect();
        }
        
        parent::render($content);
    }
    
    
    //---Widgets---//
    
    public function widget_modules() {
        
        foreach($this->modmanager->get_modules() as $mod) {
            
            if ($mod->admin) {
            
                $atribute = array();
                
                if ($mod->code == $this->uri->segment(3)) {
                    
                    $atribute['id'] = 'current';
                }
                
                $ul[] = modul_anchor('modul/'.$mod->code, $mod->title, $atribute);
            }
        }
        
        parent::render(ul($ul));
    }
    
    
    public function widget_info() {
        
        $ul[] = '<b>Версия:</b> '.$this->config->item('core_ver');
        $ul[] = '<b>Обновлено:</b> '.human_date($this->config->item('core_updated'));
        
        parent::render(ul($ul));
    }
}